package com.cheng.xbjy.dao;

import com.cheng.xbjy.entity.Article;
import com.cheng.xbjy.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface ArticleDao extends JpaRepository<Article, Long> {


    Page<Article> findByTitleLike(String title, Pageable pageable);

    @Query("select count(f) from Favorite f where f.aId = ?1")
    Integer countByArticleId(Long articleId);

    @Query("update Article a set a.browseCount=a.browseCount+1 where a.id = ?1")
    @Modifying
    void updateLook(Long articleId);

    @Query(value = "select count(1) from Favorite f where f.aId = ?1 and f.uId = ?2")
    Integer findByArticleIdAndUserId(Long articleId, Long userId);

    @Query("select  u " +
            "from User u join UserFocus uf " +
            "on u.id = uf.userFocusId " +
            "join Favorite f " +
            "on uf.userFocusId = f.uId " +
            "where f.aId = ?1 " +
            "and uf.userId = ?2")
    List<User> findUserFollow(Long articleId, Long userId);

    @Query("delete from Favorite f where f.aId = ?1 and f.uId = ?2")
    @Modifying
    void deleteByArticleIdAndUserId(Long articleId, Long userId);

    @Query(value = "insert into favorite values(?1,?2)", nativeQuery = true)
    @Modifying
    void saveByArticleIdAndUserId(Long userId, Long articleId);

    @Query("select a from Article a join Favorite f on f.aId = a.id where f.uId = ?2 and a.title like ?1")
    Page<Article> findFavoritePage(String title, Long userId, Pageable pageable);
}
